#include "StaticMeshManager.h"
#include "XML/XMLTreeNode.h"
#include "Logger/Logger.h"
#include "RenderManager.h"

#if defined (_DEBUG)
#include "Memory/MemLeaks.h"
#endif

//-------------------------------------------------
CStaticMeshManager::CStaticMeshManager()
	: m_sFilename("")
{

}

//-------------------------------------------------
CStaticMeshManager::~CStaticMeshManager()
{
	CleanUp();
}

//-------------------------------------------------
void CStaticMeshManager::CleanUp()
{
	m_StaticMeshMap.Destroy();
}

//-------------------------------------------------
bool CStaticMeshManager::Load(const std::string& _filename)
{
	m_sFilename = _filename;
	return LoadFile();
}

//-------------------------------------------------
bool CStaticMeshManager::Reload()
{
	CleanUp();
	return LoadFile();
}

//-------------------------------------------------
bool CStaticMeshManager::LoadFile()
{
	CXMLTreeNode newFile;
	if (!newFile.LoadFile(m_sFilename.c_str()))
	{
		std::string msg_error = "CStaticMeshManager::LoadFile->Error reading static meshes file: " + m_sFilename;
		LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str());

		return false;
	}

	CXMLTreeNode l_StaticMeshes = newFile["static_meshes"];
	if( l_StaticMeshes.Exists() )
	{
		uint32 l_uCount = l_StaticMeshes.GetNumChildren();
		for(uint32 i=0; i<l_uCount; ++i)
		{
			std::string l_sType = l_StaticMeshes(i).GetName();
			if(l_sType == "static_mesh")
			{
				std::string l_sName	= l_StaticMeshes(i).GetPszProperty("name", "");
				std::string l_sFile	= l_StaticMeshes(i).GetPszProperty("file", "");

				CStaticMesh* l_pStaticMesh = new CStaticMesh();
				l_pStaticMesh->Load(l_sFile);

				m_StaticMeshMap.AddResource(l_sName, l_pStaticMesh);
			}
		}
	}
	else
	{
		return false;
	}

	return true;
}

//-------------------------------------------------
void CStaticMeshManager::Render(CRenderManager* _pRM)
{
	std::vector<CStaticMesh*> l_MeshesVector = m_StaticMeshMap.GetResourcesVector();
	std::vector<CStaticMesh*>::iterator l_It = l_MeshesVector.begin();
	std::vector<CStaticMesh*>::iterator l_End = l_MeshesVector.end();

	for(;l_It != l_End; ++l_It)
	{
		(*l_It)->Render(_pRM);
	}
}